package com.dinadi.yidi.http;

import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;

import com.dinadi.yidi.R;
import com.dinadi.yidi.utils.CommonUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.Map;

/**
 * http请求类
 * Created by dell on 2016/3/21.
 */
public class ServiceUtil {

    private static int pro = 0;
    public static final int notifyID = 99;
    private static Notification.Builder builder;
    private static boolean isCreat = false;
    private static NotificationManager notificationManager;
    private static final int UpDataDownloadProgress = 999;

    public static class ServiceUtilHolder {
        public static final ServiceUtil INSTANCE = new ServiceUtil();
    }

    public ServiceUtil() {
    }

    public static final ServiceUtil getInstance() {
        return ServiceUtilHolder.INSTANCE;
    }


    private static Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UpDataDownloadProgress:
                    Log.i("tag", pro + "");
                    if (pro < 100) {
                        builder.setContentText(pro + "%");
                        builder.setProgress(100, pro, false);
                        //判断版本兼容
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                            notificationManager.notify(notifyID, builder.build());
                        }
                        handler.sendEmptyMessageDelayed(UpDataDownloadProgress, 200);
                    } else {
                        handler.sendEmptyMessage(20);
                    }
                    break;
                case 20:
                    cancleNotification();
                    break;
            }
        }
    };

    public interface
    RequestCallBack<T> {
        void onSuccess(T result);

        void onFailure(String error);
    }

    public static void requestPostData(String url, Map jsonObject, final RequestCallBack<String> requestCallBack) {

        RestClient.post(url, jsonObject, new MyHttpCallback() {
            String aa;

            @Override
            public void onSuccess(String response) {
                if (requestCallBack != null) {
                    requestCallBack.onSuccess(response);
                }
            }

            @Override
            public void onFailure(String error) {
                if (requestCallBack != null) {
                    requestCallBack.onFailure(error);
                }
            }

        });
    }

    public static void requestPostBitmap(String url, final ImageView imageView, final RequestCallBack<Bitmap> requestCallBack) {

        RestClient.postBitmap(url, new BitmapHttpCallBack() {
            @Override
            public void onSuccess(Bitmap response) {
                imageView.setImageBitmap(response);
                if (requestCallBack != null) {
                    requestCallBack.onSuccess(response);
                }
            }

            @Override
            public void onFailure(String error) {
                if (requestCallBack != null) {
                    requestCallBack.onFailure(error);
                }
            }
        });
    }


    /***
     * 下载APK
     *
     * @param url             下载APK的地址
     * @param filePath        APK 下载之后存放的路径
     * @param fileName        APK 下载之后的文件名
     * @param requestCallBack
     */
    public static void requestDownAPK(String url, String filePath, String fileName, final RequestCallBack<File> requestCallBack,
                                      final FileHttpCallback fileHttpCallback) {
        Log.i("url", url + filePath + ":" + fileName);
        RestClient.downAPK(url, new FileHttpCallback(filePath, fileName) {
            @Override
            public void onSuccess(File response) {
                if (requestCallBack != null) {
                    cancleNotification();
                    requestCallBack.onSuccess(response);
                }
                if (fileHttpCallback != null) {
                    fileHttpCallback.onSuccess(response);
                }
            }

            @Override
            public void onFailure(String error) {
                if (requestCallBack != null) {
                    cancleNotification();
                    requestCallBack.onFailure(error);
                }
                if (fileHttpCallback != null) {
                    fileHttpCallback.onFailure(error);
                }
            }

            @Override
            public void onProgress(float progress, long total) {
                if (fileHttpCallback != null) {
                    fileHttpCallback.onProgress(progress, total);
                }
                if (requestCallBack != null) {
                    if (!isCreat) {
                        Log.i("progress", progress + ":" + total);
                        creatNotification();
                        handler.sendEmptyMessage(UpDataDownloadProgress);
                        isCreat = true;
                    }
                    pro = (int) (progress * 100f);
                }

            }
        });
    }

    public static void requestGetData(String url, Map jsonObject, final RequestCallBack<String> requestCallBack) throws JSONException {

        RestClient.get(url, jsonObject, new MyHttpCallback() {

            @Override
            public void onSuccess(String response) {
                if (requestCallBack != null) {
                    requestCallBack.onSuccess(response);
                }
            }

            @Override
            public void onFailure(String error) {
                if (requestCallBack != null) {
                    requestCallBack.onFailure(error);
                }
            }


        });
    }

    public static void requestGetData2(String url, Map headJsonObject, Map jsonObject, final RequestCallBack<String> requestCallBack) throws JSONException {

        RestClient.doGet(url, headJsonObject, jsonObject, new MyHttpCallback() {

            @Override
            public void onSuccess(String response) {
                if (requestCallBack != null) {
                    requestCallBack.onSuccess(response);
                }
            }

            @Override
            public void onFailure(String error) {
                if (requestCallBack != null) {
                    requestCallBack.onFailure(error);
                }
            }


        });
    }


    public static void uploadFile(String url, File file, JSONObject jsonObject, String fileTag, String fileName, final RequestCallBack<String> requestCallBack) throws JSONException {
        RestClient.uploadFile(url, jsonObject, fileTag, fileName, file, new MyHttpCallback() {
            @Override
            public void onSuccess(String response) {
                if (requestCallBack != null) {
                    requestCallBack.onSuccess(response);
                }
            }

            @Override
            public void onFailure(String error) {
                if (requestCallBack != null) {
                    requestCallBack.onFailure(error);
                }
            }
        });
    }


    private static void creatNotification() {
        builder = new Notification.Builder(CommonUtil.getContext())
                .setSmallIcon(R.drawable.app_icon)
                .setContentText("0%")
                .setContentTitle(CommonUtil.getContext().getResources().getString(R.string.app_name))
                .setProgress(100, 0, false);
        notificationManager = (NotificationManager) CommonUtil.getContext().getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            notificationManager.notify(notifyID, builder.build());
        }
    }

    private static void cancleNotification() {
        if (notificationManager == null) {
            notificationManager = (NotificationManager) CommonUtil.getContext().getSystemService(Context.NOTIFICATION_SERVICE);
        }
        notificationManager.cancel(notifyID);
        isCreat = false;
    }


}
